<?php

namespace App\Http\Controllers;

use App\Brand;
use App\Goods;
use App\GoodsCategory;
use Illuminate\Http\Request;

class BrandController extends Controller
{
    public $goods_cats;
    public function __construct()
    {
        $goods_category_controller = new GoodsCategoryController();
        $this->goods_cats = $goods_category_controller->getList(GoodsCategory::where('id','!=',9999)->orderBy('sort','asc')->get(), 0, 0);//所有分类列表
    }

    public function _list(Request $request){
        $cond = [];
        $search_data = [];
        if($request->filled('name')){
            $cond[] = ['brand.name','like','%'.$request->name.'%'];
            $search_data['name'] = $request->name;
        }
        if($request->filled('cat_id')){
            $cond[] = ['cat_id','=',$request->cat_id];
            $search_data['cat_id'] = $request->cat_id;
        }
        $list = $this->getList(
            Brand::where($cond)
                ->select(
                    'brand.id as id',
                    'brand.name as name',
                    'brand.logo as logo',
                    'goods_category.name as cat_name',
                    'brand.remark as remark',
                    'brand.created_at as created_at',
                    'brand.is_show as is_show'
                )
                ->leftJoin('goods_category', 'brand.cat_id', '=', 'goods_category.id')
                ->orderBy('brand.sort','asc')->get(),
            0, 0);//所有品牌

        return view('Brand.list',[
            'list' => $list,
            'search_data' => $search_data,
            'cats' => $this->goods_cats
        ]);
    }

    public function edit(Request $request){
        $id = $request->filled('id') ? $request->id : null;

        if(!$_POST){
            $info = Brand::find($id);
            return view('Brand.edit', [
                'cats' => $this->goods_cats,
                'info' => $info
            ]);
        }

        $name = $request->filled('name') ? $request->name : null;
        $remark = $request->filled('remark') ? $request->remark : null;
        $logo = $request->filled('logo') ? $request->logo : '';
        $cat_id = $request->filled('cat_id') ? $request->cat_id : null;
        $sort = $request->filled('sort') ? $request->sort : 100;//默认排序100
        $is_show = $request->filled('is_show') ? $request->is_show : 1;//默认展示1

        if($id){
            //update
            Brand::where('id', $id)->update([
                'name' => $name,
                'remark' => $remark,
                'cat_id' => $cat_id,
                'sort' => $sort,
                'is_show' => $is_show,
                'logo' => $logo
            ]);
        }else{
            //add
            $brand = new Brand;
            $brand->name = $name;
            $brand->remark = $remark;
            $brand->cat_id = $cat_id;
            $brand->sort = $sort;
            $brand->is_show = $is_show;
            $brand->logo = $logo;
            $brand->save();
        }

        return json_encode([
            'code' => 1,
            'msg' => 'success'
        ]);
    }

    public function del(Request $request){
        $id = $request->filled('id') ? $request->id : null;

        if(!$id)
            return json_encode([
                'code' => 0,
                'msg' => 'ID can not be null'
            ]);

        $id_arr = explode(',', $id);
        foreach($id_arr as $v){
            if(!Goods::where('brand_id', $v)->get()->isEmpty()){
                return json_encode([
                    'code' => 0,
                    'msg' => '删除失败，品牌【'.Brand::find($v)->name.'】下面还有商品数据，请先删除干净'
                ]);
            }
        }
        foreach($id_arr as $v){
            //删除该品牌
            Brand::destroy($v);
        }

        return json_encode([
            'code' => 1,
            'msg' => 'success'
        ]);
    }

    public function getBrandListByGoodsCatId(Request $request){
        $cat_id = $request->filled('cat_id') ? $request->cat_id : null;
        $list = Brand::where('cat_id', $cat_id)->get();
        return json_encode([
            'code' => 1,
            'list' => $list
        ]);
    }

    /**
     * @param $data 原始数据
     * @param $pid 起始父级ID(默认是0)
     * @param $depth 目录深度(默认是1)
     * @return array 返回列表（带层级数）
     */
    public function getList($data, $pid, $depth){
        static $list = [];//最终存放结果的集合，
        foreach($data as $v){
            if($v->pid == $pid){
                $v->depth = $depth;//给元素对象添加depth元素
                $list[] = $v;
                $this->getList($data, $v->id, $depth+1);
            }
        }
        return $list;
    }

    public function uploadImg(Request $request){
        if($request->hasFile('upload_logo') && $request->file('upload_logo')->isValid()){
            $img_url = QclouduUpload(md5(uniqid(md5(microtime(true)),true)), $request->file('upload_logo')->getRealPath());
            return json_encode([
                'code' => 1,
                'msg' => 'success',
                'img_url' => $img_url
            ]);
        }else{
            return json_encode([
                'code' => 0,
                'msg' => 'Upload error,please try again'
            ]);
        }
    }

}
